<template>
  <view class="container">
    <navigationBar custom :showBack="false">
      <view class="top">
        <view class="top-left">
          <dropdown :arrowColor="2" :value="dropdownValue" :list="dropdownListRef" @select="onChangeDropdown">
            <view class="top-left-value">
              <view class="top-left-icon" v-if="dropdownStatus">
                <image src="/@/static/images/online.png" v-if="dropdownStatus===1"/>
                <image src="/@/static/images/offline.png" v-else-if="dropdownStatus===2"/>
                <image src="/@/static/images/fault.png" v-else/>
              </view>
              {{ dropdownName }}
            </view>
          </dropdown>
        </view>
        <view class="top-right" @click="onEnterMessage">
          <image v-if="haveMessage" src="/@/static/images/xiaoxi-1.png"></image>
          <image v-else src="/@/static/images/xiaoxi.png"></image>
        </view>
      </view>
    </navigationBar>

    <view class="car-box">
      <image src="/@/static/images/car.png"></image>
    </view>

    <view class="map-box">
      <view class="map-address">{{ mapInfoRef.latitude }} {{ mapInfoRef.longitude }}</view>
      <view class="map">
        <customMap :mapInfo="mapInfoRef"></customMap>
      </view>

    </view>

    <view class="main">
      <view class="main-item" v-for="item in moduleListRef" :key="item.key">
        <view class="main-item-title">{{ item.title }}</view>
        <view class="main-item-list">
          <view class="main-item-list-item" v-for="item1 in item.list" :key="item1.key">
            <view class="main-item-list-item-icon">
              <image :src="item1.icon"></image>
            </view>
            <view class="main-item-list-item-title">{{ item1.value }}</view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import {onHide, onLoad, onShow, onUnload} from "@dcloudio/uni-app";
import {ref} from "vue"
import drivingMode from "/src/static/images/jiashimoshi.png"
import speed from "/src/static/images/chesu.png"
import gear from "/src/static/images/dangwei.png"
import vehicleMode from "/src/static/images/cheliangmoshi.png"
import power from "/src/static/images/dianliang.png"
import fuelConsumption from "/src/static/images/haoyouliang.png"
import rollerBrushDrying from "/src/static/images/gunshuahonggan.png"
import vacuuming from "/src/static/images/xicheng.png"
import rollerBrushPosition from "/src/static/images/gunshuaweizhi.png"
import {getLocalStorage, setLocalStorage, showMessage} from "/@/utils/util";
import locationIcon from "/@/static/images/cheliangdingwei-zaixian1.png";
import {STORAGE_KEY} from "/@/config/constant";
import {userApi} from "/@/api/login";
import {basicState} from "/@/api/iHome";


const mapInfo = {
  longitude: 116.397128,
  latitude: 39.916527,
  scale: 12,
  markers: [{
    id: 0,
    longitude: 116.397128,
    latitude: 39.916527,
    iconPath: locationIcon,
    width: '24',
    height: '24',
  }],
}

const moduleList = [
  {
    title: "基础状态", key: 1, list: [
      {icon: drivingMode, value: '', key: 'drivingMode'},
      {icon: speed, value: '', key: 'speed'},
      {icon: gear, value: '', key: 'gear'},
      {icon: vehicleMode, value: '', key: 'vehicleMode'},
      {icon: power, value: '', key: 'power'},
      {icon: fuelConsumption, value: '', key: 'fuelConsumption'},
      {icon: '', value: '', key: 'gps'},
      {icon: '', value: '', key: 'altitude'},
    ]
  },
  {
    title: "滚刷状态", key: 2, list: [
      {icon: rollerBrushDrying, value: '', key: 'rollerBrushDrying'},
      {icon: vacuuming, value: '', key: 'vacuuming'},
      {icon: rollerBrushPosition, value: '', key: 'location'},
      {icon: '', value: '', key: 'pitch'},
    ]
  },
]

const moduleListRef = ref(moduleList)
const dropdownListRef = ref([])
const haveMessage = ref(false)
const dropdownValue = ref(1)
const dropdownName = ref('')
const dropdownStatus = ref(2)
const dropdownSelectRef = ref({})
const mapInfoRef = ref(mapInfo)
let refreshInterval = null;

onLoad(() => {
  loadDropdownList()
})

onShow(() => {
  console.log('onShow.setInterval.refreshDeviceState')
  refreshInterval = setInterval(refreshDeviceState, 5000);
  console.log(refreshInterval)
});

onHide(() => {
  if (refreshInterval) {
    console.log('onHide.clearInterval.refreshDeviceState')
    clearInterval(refreshInterval);
    refreshInterval = null;
  }
});

onUnload(() => {
  if (refreshInterval) {
    console.log('onUnload.clearInterval.refreshDeviceState')
    clearInterval(refreshInterval);
    refreshInterval = null;
  }
});

const loadDropdownList = () => {
  let userInfo = JSON.parse(getLocalStorage(STORAGE_KEY.userInfo));
  console.log(userInfo)
  if (!userInfo || !userInfo.userid) {
    showMessage('用户信息获取失败!')
    return
  }
  let reqData = {
    userId: userInfo.userid
  }
  userApi(reqData).then(res => {
    if (res && res.data) {
      // console.log('机器清单信息', res.data)
      dropdownListRef.value = res.data.map(item => ({
        mac: item.robotMac,
        value: item.robotId,
        label: item.robotName,
        status: (item.online === 1 ? (item.fault === 1 ? 3 : 1) : 2),
      }));
      dropdownSelectRef.value = dropdownListRef.value.find(item => {
        return item.value === dropdownValue.value
      })
      dropdownName.value = (dropdownSelectRef.value)?.label || ''
      dropdownStatus.value = (dropdownSelectRef.value)?.status || 2
      // console.log('loadBasicState', dropdownSelectRef.value)
      loadDeviceState(dropdownSelectRef.value);
    } else {
      showMessage('设备列表获取失败!')
    }
  })
}


const loadDeviceState = (params) => {
  // console.log('params', params)
  if (!params && !params.mac) {
    showMessage('设备Mac地址获取失败!')
    return
  }
  params.deviceId = params.mac
  params = Object.keys(params).reduce((acc, key) => {
    if (key === 'deviceId') {
      acc[key] = params[key];
    }
    return acc;
  }, {});
  setLocalStorage(STORAGE_KEY.dropdownCurrentDeviceId, params)
  // console.log('DeviceStateReq', params)
  basicState(params).then(res => {
    if (!res || !res.data
        || !res.data.dataJson
        || !res.data.dataJson.statusData
        || !params.deviceId === res.data.dataJson.macAddress) {
      showMessage('设备状态获取失败!')
      return
    }
    // console.log('basicState', res.data)
    // 深拷贝当前 moduleList
    const newModuleList = JSON.parse(JSON.stringify(moduleListRef.value));
    const statusData = res.data.dataJson.statusData;
    const chassis = statusData.chassis;
    const gps = statusData.gps;
    mapInfoRef.value.longitude = getValidLatOrLng((gps)?.longitude || '')
    mapInfoRef.value.latitude = getValidLatOrLng((gps)?.latitude || '')
    const adapt = statusData.adapt;
    const brush = statusData.brush;
    // console.log(chassis, gps, adapt, brush)
    // 遍历并更新值
    newModuleList.forEach(category => {
      if (category.title === '基础状态') {
        category.list.forEach(item => {
          if (item.key === 'drivingMode') {
            item.value = (chassis)?.autonomous || '';
          } else if (item.key === 'speed') {
            item.value = (chassis)?.speeds || '';
          } else if (item.key === 'gear') {
            item.value = (chassis)?.gear || '';
          } else if (item.key === 'vehicleMode') {
            item.value = (chassis)?.vehicleStatus || '';
          } else if (item.key === 'power') {
            item.value = (chassis)?.soc || '';
          } else if (item.key === 'fuelConsumption') {
            item.value = (chassis)?.oil || '';
          } else if (item.key === 'gps') {
            let lng = (gps)?.longitude || '';
            let lat = (gps)?.latitude || '';
            item.value = lat + '\n' + lng;
          } else if (item.key === 'altitude') {
            item.value = (gps)?.altitude || '';
          }
        });
      } else {
        category.list.forEach(item => {
          if (item.key === 'rollerBrushDrying') {
            let brushSpeedLevel = getBrushSpeedLevel(brush);
            item.value = brushSpeedLevel;
          } else if (item.key === 'vacuuming') {
            item.value = (brush)?.brushMode || '';
          } else if (item.key === 'location') {
            item.value = (adapt)?.location || '';
          } else if (item.key === 'pitch') {
            item.value = (adapt)?.pitch || '';
          }
        });
      }
    });
    moduleListRef.value = newModuleList;
  })
}

const refreshDeviceState = () => {
  let userInfo = JSON.parse(getLocalStorage(STORAGE_KEY.userInfo));
  if (userInfo && userInfo.userid) {
    let reqData = {
      userId: userInfo.userid
    }
    userApi(reqData).then(res => {
      if (res && res.data) {
        // console.log('机器清单信息', res.data)
        dropdownListRef.value = res.data.map(item => ({
          mac: item.robotMac,
          value: item.robotId,
          label: item.robotName,
          // 如果在线并且不是故障展示在线否则展示离线，如果在线并且是故障展示故障
          status: (item.online === 1 ? (item.fault === 1 ? 3 : 1) : 2),
        }));
        dropdownSelectRef.value = dropdownListRef.value.find(item => {
          return item.value === dropdownValue.value
        })
        dropdownName.value = (dropdownSelectRef.value)?.label || ''
        dropdownStatus.value = (dropdownSelectRef.value)?.status || 2
      }
    })
  }

  let params = JSON.parse(getLocalStorage(STORAGE_KEY.dropdownCurrentDeviceId))
  if (!params) {
    showMessage('设备Mac地址获取失败!')
    return
  }
  // console.log('DeviceStateReq', params)
  basicState(params).then(res => {
    if (!res || !res.data
        || !res.data.dataJson
        || !res.data.dataJson.statusData
        || !params.deviceId === res.data.dataJson.macAddress) {
      // showMessage('设备状态获取失败!')
      return
    }
    // console.log('basicState', res.data)
    // 深拷贝当前 moduleList
    const newModuleList = JSON.parse(JSON.stringify(moduleListRef.value));
    const statusData = res.data.dataJson.statusData;
    const chassis = statusData.chassis;
    const gps = statusData.gps;
    mapInfoRef.value.longitude = getValidLatOrLng((gps)?.longitude || '')
    mapInfoRef.value.latitude = getValidLatOrLng((gps)?.latitude || '')
    const adapt = statusData.adapt;
    const brush = statusData.brush;
    // console.log(chassis, gps, adapt, brush)
    // 遍历并更新值
    newModuleList.forEach(category => {
      if (category.title === '基础状态') {
        category.list.forEach(item => {
          if (item.key === 'drivingMode') {
            item.value = (chassis)?.autonomous || '';
          } else if (item.key === 'speed') {
            item.value = (chassis)?.speeds || '';
          } else if (item.key === 'gear') {
            item.value = (chassis)?.gear || '';
          } else if (item.key === 'vehicleMode') {
            item.value = (chassis)?.vehicleStatus || '';
          } else if (item.key === 'power') {
            item.value = (chassis)?.soc || '';
          } else if (item.key === 'fuelConsumption') {
            item.value = (chassis)?.oil || '';
          } else if (item.key === 'gps') {
            let lng = (gps)?.longitude || '';
            let lat = (gps)?.latitude || '';
            item.value = lat + '\n' + lng;
          } else if (item.key === 'altitude') {
            item.value = (gps)?.altitude || '';
          }
        });
      } else {
        category.list.forEach(item => {
          if (item.key === 'rollerBrushDrying') {
            let brushSpeedLevel = getBrushSpeedLevel(brush);
            item.value = brushSpeedLevel;
          } else if (item.key === 'vacuuming') {
            item.value = (brush)?.brushMode || '';
          } else if (item.key === 'location') {
            item.value = (adapt)?.location || '';
          } else if (item.key === 'pitch') {
            item.value = (adapt)?.pitch || '';
          }
        });
      }
    });
    moduleListRef.value = newModuleList;
  })
}

const getBrushSpeedLevel = (brush) => {
  return Number((brush)?.brushSpeed) || "0"; // 强制转为数字，默认为 0
}

/*const getBrushSpeedLevel = (brush) => {
  let brushSpeed = Number((brush)?.brushSpeed) || 0; // 强制转为数字，默认为 0
  let brushSpeedLevel = '';
  if (brushSpeed === 0) {
    brushSpeedLevel = '0档';
  } else if (brushSpeed > 0 && brushSpeed <= 85) {
    brushSpeedLevel = '1档';
  } else if (brushSpeed >= 86 && brushSpeed <= 170) {
    brushSpeedLevel = '2档';
  } else if (brushSpeed > 170) {
    brushSpeedLevel = '3档';
  }
  return brushSpeedLevel;
}*/

const getValidLatOrLng = (str) => {
  const cleaned = str ? str.replace(/[^0-9.-]/g, '') : '';
  const num = parseFloat(cleaned);
  if (isNaN(num)) return null;
  // 保留 7 位小数，并转换为数值类型
  return num.toFixed(7);
}

const onEnterMessage = () => {
  uni.navigateTo({
    url: '/pages/message/message'
  })
}

const onChangeDropdown = (e) => {
  dropdownValue.value = e.value
  dropdownName.value = e.label
  dropdownStatus.value = e.status
  // console.log(e)
  loadDeviceState(e)
}
</script>

<style lang="scss" scoped>
@import "index";
</style>
